package com.smart.community.feign.error;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义错误解码器
 * 
 * 统一处理Feign调用错误，提供更好的错误信息
 * 根据不同的HTTP状态码返回相应的异常类型
 * 
 * @author Wu.Liang
 * @version 2.0.0
 * @since 2025-08-28
 */
@Slf4j
public class CustomErrorDecoder implements ErrorDecoder {
    
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String responseBody = "";
            if (response.body() != null) {
                responseBody = feign.Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            }
            
            log.warn("Feign调用失败 - 方法: {}, 状态码: {}, 响应: {}", methodKey, response.status(), responseBody);
            
            switch (response.status()) {
                case 400:
                    return FeignException.errorStatus("请求参数错误", response);
                case 401:
                    return FeignException.errorStatus("认证失败", response);
                case 403:
                    return FeignException.errorStatus("权限不足", response);
                case 404:
                    return FeignException.errorStatus("服务不存在", response);
                case 500:
                    return FeignException.errorStatus("服务器内部错误", response);
                case 503:
                    return FeignException.errorStatus("服务不可用", response);
                default:
                    return FeignException.errorStatus("服务调用失败", response);
            }
        } catch (IOException e) {
            log.error("解析Feign错误响应失败", e);
            return FeignException.errorStatus("服务调用失败", response);
        }
    }
}
